import React from 'react';
import { Upload, Modal, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { createImg } from '@/services/ant-design-pro/api';
import { getUploadToken } from '@/services/ant-design-pro/api'
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}

export class PicturesWall extends React.Component {
  // constructor(props) {
  //   super(props);
  //   this.state = {
  //     previewVisible: false,
  //     previewImage: '',
  //     previewTitle: '',
  //     fileList: this.props.fileList,
  //   };
  // }

  state = {
    previewVisible: false,
    previewImage: '',
    previewTitle: '',
    fileList: this.props.fileList,
    token: '',
    host: '',
    key: ''
    // fileList: [
    //   {
    //     uid: '-1',
    //     name: 'image.png',
    //     status: 'done',
    //     url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    //   },
    //   {
    //     uid: '-2',
    //     name: 'image.png',
    //     status: 'done',
    //     url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    //   },
    // ],
  };
  componentDidMount() {
    this.getToken()
  }

  componentWillReceiveProps(props) {
    if (this.state.fileList.length !== props.fileList.length) {
      const fileList = props.fileList.map(val => ({
        ...val,
        uid: val.id,
        url: val.path,
        // status: 'done'
      }))
      this.setState({ fileList });
    }
  }

  getToken = async () => {
    try {
      const res = await getUploadToken()
      if (res.data && res.data.uploadToken) {
        this.setState({
          token: res.data.uploadToken,
          host: res.data.host,
          key: res.data.key
        })
      } else {
        message.error("获取token失败请重试")
      }
    } catch (err) {
      message.error("网络出错，请重试")
    }
  }

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    });
  };

  handleChange = async ({ file, fileList }) => {
    const { status, response } = file;
    if (status === 'done') {
      const host = this.state.host
      const params = {
        bind_type: this.props.bindType === 'estate' ? 0 : 1,
        bind_id: +this.props.bindId,
        store: 'oss', // 默认选择server
        path: `${host}/${response.key}`,
      };
      await createImg({ data: params });
    }
    // always setState
    this.setState({ fileList: [...fileList] });
  };


  generatorToken = (file) => {
    const key = this.state.key + file.name
    return {
      token: this.state.token,
      key: key
    }
  }
  render() {
    const { fileList, previewVisible, previewImage, previewTitle } = this.state;

    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>上传图片</div>
      </div>
    );
    return (
      <>
        <Upload
          name="file"
          action={`//upload-z2.qiniup.com`}
          data={this.generatorToken}
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
          onRemove={this.props.onRemove && this.props.onRemove}
        >
          {fileList.length >= 8 ? null : uploadButton}
        </Upload>
        <Modal
          visible={previewVisible}
          title={previewTitle}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </>
    );
  }
}

export default PicturesWall